<template>
  <div class="f_div">
    <div class="t_div">运营管理 / <a href="#">回单</a></div>
    <el-container>

      <el-header class="header2">
        <div class="h_div">
          <div class="h_in_vid">
            <el-form ref="form" :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="订单状态：">
                <el-input v-model="value" placeholder="请输入始发地"></el-input>
              </el-form-item>
              <el-form-item label="回单状态：">
                <el-input v-model="value1" placeholder="请输入目的地"></el-input>
              </el-form-item>
              <el-form-item label="发货日期：">
                <el-date-picker v-model="value2" type="datetimerange" range-separator="To"
                  start-placeholder="请选择日期" end-placeholder="请选择日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
              <el-form-item label="签收日期：">
                <el-date-picker v-model="value2" type="datetimerange" range-separator="To"
                  start-placeholder="请选择日期" end-placeholder="请选择日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"></el-date-picker>
              </el-form-item>
              <el-form-item label="搜索：">
                <el-input v-model="value3" placeholder="请输入关键字搜索"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="tjian">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>


            </el-form>
          </div>
        </div>
      </el-header>
      <el-main class="main">
        <el-table height="442px" :data="tableData" style="width: 100%" row-key="depart_id" default-expand-all stripe
          :header-cell-style="{
              background: '#F7F7F7',
              color: '#999',
              textAlign: 'center',
            }" :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="ord_number" label="订单号" width="150"></el-table-column>
          <el-table-column prop="client_name" label="客户" width="120"></el-table-column>
          <el-table-column prop="receipt_type" label="回单状态" width="120">
            <template #default="scope">
              <span>{{ formatReceiptState(scope.row.receipt_type) }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="ord_state" label="订单状态" width="120">
            <template #default="scope">
              <span>{{ formatOrderState(scope.row.ord_state) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="receipt_num" label="回单份数" width="120"></el-table-column>
          <el-table-column prop="ord_startaddress" label="发货地址" width="170"></el-table-column>
          <el-table-column prop="ord_destination" label="收货地址" width="170"></el-table-column>
          <el-table-column prop="sign_num" label="签收数量" width="120"></el-table-column>
          <el-table-column prop="sign_by" label="签收人" width="120"></el-table-column>
          <el-table-column prop="sign_time" label="签收时间" width="120"></el-table-column>
          <el-table-column label="操作">
            <template #default="scoped">
              <el-button type="text" size="small" @click="SC(scoped.row.receipt_id)">上传回单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[4, 6, 8, 10]"
            :size="size" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.length"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-main>
    </el-container>
  </div>
  <el-dialog v-model="dialogTableVisible" title="" width="800">
                        <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="快递公司:" prop="courier_companies">
          <el-select v-model="tableData[0].courier_companies" placeholder="请选择" :teleported="false">
            <el-option v-for="item in options" :key="item.dict_code" :label="item.dict_label"
              :value="item.dict_value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="邮寄单号:">
          <el-input v-model="tableData[0].mailing_number" placeholder="请输入内容" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="寄件时间">
          <el-date-picker v-model="tableData[0].mailing_time" type="date" placeholder="Pick a day" :size="size" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="上传回单" prop="receipt">
          <el-upload action="http://localhost:5261/api/Company/Upload" list-type="picture-card" :auto-upload="true"
            v-model:file-list="rulelist" :limit="1" :on-exceed="handleExceed" ref="upload"
            :on-success="handleUploadSuccess" :on-error="handleUploadError" class="form_content" accept=".jpg,.png">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                    <el-icon>
                      <Download />
                    </el-icon>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <div class="form_content" style="color:#CCCCCC">建议上传图片大小不超过2MB，格式只能是*.jpg,*.png</div>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" style="max-width: 100%; height: auto" />
          </el-dialog>
        </el-form-item>
      </el-col>
    </el-row>
                            <el-button type="primary" style="margin-left: 650px;" @click="BC">保存</el-button>
                        </el-dialog>
</template>




<script>
import { ref, reactive, resolveComponent, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import $http from '@/axios/base.js';


export default {
  setup() {
    const receipt_Meter = reactive({
      courier_companies: 0,
      mailing_number: "",
      mailing_time: "",
      receipt: "",
    });


    let tableData = ref([]);
    let value = ref("");
    let value1 = ref("");
    let value2 = ref("");
    let value3 = ref("");
    let options = ref([]);
    let currentPage = ref("1");
    let pageSize = ref("10");
    let router = useRouter();
    let ord_id = ref();
    let sign_id = ref();
    let dialogTableVisible = ref(false);
    let upload = ref(null);

    let rulelist = ref([
      {
        name: "TX.jpg",
        url: "http://localhost:5261/images/TX.jpg",
      },
    ]);

    function formatReceiptState(status) {
      switch (status) {
        case 0:
          return '未回收';
        case 1:
          return '已回收';
        case 2:
          return '已寄出';
        case 4:
          return '已确认';
      }
    }

    function formatOrderState(status) {
      switch (status) {
        case 1:
          return '待接单';
        case 2:
          return '待提货';
        case 3:
          return '待发车';
        case 4:
          return '运输中';
        case 5:
          return '待签收';
        case 6:
          return '已完成';
        case 7:
          return '已取消';
        case 8:
          return '已拒绝';
      }
    }

    function SC(receipt_id) {
      dialogTableVisible.value = true
      tableData.receipt_id = receipt_id;
      alert(receipt_id);
    }

    function BC() {
      receipt_Meter.courier_companies = tableData.value[0].courier_companies;
      receipt_Meter.mailing_number = tableData.value[0].mailing_number;
      receipt_Meter.mailing_time = tableData.value[0].mailing_time;
      receipt_Meter.receipt = tableData.value[0].receipt;
      receipt_Meter.receipt_id = tableData.receipt_id;
      console.log(tableData.value[0].courier_companies);
      $http.put("http://localhost:5261/api/Receipt_meter/BC", receipt_Meter).then((res) => {
        if (res) {
          location.reload();
          setTimeout(() => {
            ElMessage.success("操作成功！！！");
          }, 1000);
          HD();
        } else {
          ElMessage.error("操作失败！！！")
        }
      })
    }

    function HD(id) {
      $http.put(`http://localhost:5261/api/Order/HD/${id}`).then((res) => {
        alert('已发车');
      }).catch((err) => {
        console.log("错误：" + err)
      })
    }

    const codeVisible = true;
    const dialogImageUrl = ref("");
    const dialogVisible = ref(false);
    const disabled = ref(false);

    function handleRemove(file) {
      receipt_Meter.receipt = "";
      upload.value.clearFiles();
    }

    function handlePictureCardPreview(file) {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    }

    function handleDownload(file) {
      var now = new Date();

      // 获取年、月、日、时、分、秒
      var year = now.getFullYear();
      var month = now.getMonth() + 1; // 注意月份是从 0 开始的
      var day = now.getDate();
      var imageUrl = file.url;
      var link = document.createElement("a");
      link.href = imageUrl;
      link.download =
        "回单" + year + month + day + getRandomString(8) + ".jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    function handleExceed(files) {
      // 当上传的文件数量超过限制时，清空已上传的文件列表，并上传最新的文件
      upload.value.clearFiles();
      const file = files[0]; // 获取最新的文件
      file.uid = Date.now(); // 为文件生成唯一的标识符
      upload.value.handleStart(file); // 开始上传最新的文件
      upload.value.submit();
    }

    const handleUploadSuccess = (response, file, fileList) => {
      // 处理上传成功的逻辑，如显示成功消息或更新UI
      console.log("上传成功", response, file, fileList);
      rulelist.url = response.result.url;
      receipt_Meter.receipt = response.result.url;
    };

    const handleUploadError = (error, file, fileList) => {
      // 处理上传失败的逻辑，如显示错误消息或更新UI
      console.error("上传失败", error, file, fileList);
      ElMessage.error("上传失败，文件大小或类型不符合要求");
    };

    function show() {
      $http.get(`http://localhost:5261/api/Receipt_meter/GetReceipt_meter/${currentPage.value},${pageSize.value}`)
        .then((res) => {
          tableData.value = res;
          res.forEach((item, index) => {
            GetSign_id(item.sign_id, index);
            GetOrd_id(item.ord_id, index)
          });
        })
        .catch((err) => console.log(err));
    }

    const GetSign_id = (id, index) => {
      $http.get(`http://localhost:5261/api/Receipt_meter/GetSign_id/${id}`)
        .then((res) => {
          Object.assign(tableData.value[index], res);
          console.log(tableData.value[index]);
          tableData.value[index].sign_time = new Date(tableData.value[index].sign_time).toISOString().slice(0, 10).toString();
        })
        .catch((err) => console.log(err))
    }

    const GetOrd_id = (id, index) => {
      $http.get(`http://localhost:5261/api/Receipt_meter/GetOrd_id/${id}`)
        .then((res) => {
          Object.assign(tableData.value[index], res);
          console.log(tableData.value[index]);
        })
        .catch((err) => console.log(err))
    }

    onMounted(() => {
      show();
      showMailing("快递公司");
    });

    function showMailing(value) {
      axios
        .get("http://localhost:5261/api/Sys_Dict_data/Get_Dict_Types", {
          params: {
            Dict_name: value,
          },
        })
        .then((res) => {
          if (value == "快递公司") options.value = res.data;
        })
        .catch((err) => console.log(err));
    }

    function tjian() {
      $http.get(`http://localhost:5261/api/Arrival_meter/Arrival_condition/${currentPage.value},${pageSize.value}?Origin_place=${value.value}&Det_place=${value1.value}&RealityGet_time=${value2.value}&value2=${value3.value}`)
        .then((res) => {
          tableData.value = res;
          console.log(res);
          console.log("=======");
          res.forEach((item, index) => {
            console.log(item.billol_Id);
            getBill_ol(item.billol_Id, index)
          });
          ArricalCount();
        })
        .catch((err) => console.log(err));
    }

    function ArricalCount() {
      $http.get(`http://localhost:5261/api/Receipt_meter/Count?Sign_time=${value2.value}&value2=${value1.value}`).then((res) => {
        // count.value = res;
        // console.log(count.value);
      }).catch((err) => {
        console.log("错误：" + err);
      })
    }
    ArricalCount();

    const searchForm = reactive({
      level: "1",
      dateRange: "",
      keyword: "",
    });

    let currentRow = ref(null);


    function handleSearch() {
      console.log(searchForm);
    }

    function handleReset() {
      // 重置表单
      searchForm.level = "";
      searchForm.dateRange = "";
      searchForm.keyword = "";
      // 重置表格数据
      // ...
    }

    function handlePageChange(val) {
      currentPage.value = val;
    }

    return {
      value,
      value1,
      value2,
      value3,
      tableData,
      receipt_Meter,
      searchForm,
      currentPage,
      pageSize,
      handleSearch,
      handleReset,
      handlePageChange,
      currentRow,
      show,
      tjian,
      formatReceiptState,
      formatOrderState,
      ArricalCount,
      SC,
      HD,
      ord_id,
      sign_id,
      dialogTableVisible,
      handleRemove,
      handleExceed,
      handlePictureCardPreview,
      handleDownload,
      codeVisible,
      dialogImageUrl,
      dialogVisible,
      disabled,
      showMailing,
      options,
      BC,
      handleUploadSuccess,
      handleUploadError,
      rulelist,
      upload
    };
  },
};
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: right;
  margin-top: 20px;
}

.t_div {
  margin-bottom: 20px;
  text-align: left;
  font-size: 14px;
  color: #b3b4b6;
}

a {
  text-decoration: none;
}

.f_div {
  padding: 0px 50px;
}

.h_div {
  height: 39px;
}

.h_in_vid {
  width: 1400px;
  height: 20px;
  margin-top: 20px;
  display: flex;
}

.header {
  background-color: #ffffff;
  border-radius: 10px 10px 0px 0px;
}

.header2 {
  background-color: #ffffff;
}

.main {
  background-color: #ffffff;
  border-radius: 0px 0px 10px 10px;
  height: 650px;
}
.el-header{
  height: 100px;
}
</style>